﻿using System;
using System.Collections.ObjectModel;
using System.Windows;
using WPF数据采集系统.Base;

namespace WPF数据采集系统
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            GlobalMonitor.Start(
            () =>
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    new MainWindow().Show();
                });
            },
            (msg) =>
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    MessageBox.Show("错误原因:" + msg + " 请确认PLC设置后再试!", "系统启动失败");
                    //Application.Current.Shutdown();
                });
            });
        }
        protected override void OnExit(ExitEventArgs e)
        {
            base.OnExit(e);
        }
        /// <summary>
        /// 换样式 （这个方法是写在Application文件中的）
        /// </summary>
        /// <param name="newPaths">要加入的新样式文件路径</param>
        /// <param name="oldxamls">要删除的老的样式文件路径</param>
        public void ApplySkin(string newPaths, string oldxamls)
        {
            Collection<ResourceDictionary> mergedDicts = base.Resources.MergedDictionaries;
            string[] ss = oldxamls.Split(',');
            if (ss.Length > 0)
            {
                foreach (var path in ss)
                {
                    if (mergedDicts.Count > 0 && path.Trim() != "")
                    {
                        foreach (var item in mergedDicts)
                        {
                            if (item.Source == null)//item.Source.OriginalString.Trim().EndsWith(path.Trim())
                            {
                                mergedDicts.Remove(item);
                                break;
                            }
                        }
                    }
                }
            }
            if (newPaths != "")
            {
                try
                {
                    string[] newss = newPaths.Split(',');
                    if (newss.Length > 0)
                    {
                        foreach (var item in newss)
                        {
                            Uri skinDictionaryUri = new Uri(item, UriKind.Relative);
                            ResourceDictionary skinDict = new ResourceDictionary();
                            //ResourceDictionary skinDict = Application.LoadComponent(skinDictionaryUri) as ResourceDictionary;
                            skinDict.Source = skinDictionaryUri;

                            mergedDicts.Add(skinDict);
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("dsds:" + ex.Message);
                }
            }
        }
    }
}
